// pages/drugApplication/index.js
const app = getApp()
import {
  ApiGetMedicineList
} from '../../api/index'
import {
  getMedicineFrequencyData,
  getMedicineTakeTypeData,
  getJADataCN
} from "../../api/docIndex"
Page({

  /**
   * 页面的初始数据
   */
  data: {
    $path: app.globalData.$path,
    medicine: [],
    ops: {
      checkResult: []
    },
    params: {
      size: 30,
      page: 1,
      finish: false,
    },
    medicineArr: [],
    sum: 0,
    active: '001',
    finish: false,
    loading: false,
    checkData: []
  },

  onChangeDosesNumber(e) {
    this.setData({
      dosesNumber: e.detail
    })
  },

  onSearch(e) {
    this.setData({
      'params.page': 1
    })
    this.getMedicList(this.data.active, e.detail)
  },

  onChangeName(event) {
    console.log(event);
    let val = event.currentTarget.dataset.v
    let data = this.data.checkData.find(item => {
      if (val.id == item.id) {
        return item
      }
    })
    if (!data) {
      val.dosageUnit = 'g'
      this.data.checkData.push(val)
      wx.showToast({
        title: '添加成功',
      })
    }
    this.setData({
      checkData: this.data.checkData
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */

  //加载更多
  onLoadMore() {
    if (this.data.loading || this.data.params.finish) return
    this.data.params.page += 1
    this.getMedicList(this.data.active)
  },
  //删除
  delItem(e) {
    let val = e.currentTarget.dataset.v
    let index = this.data.checkData.findIndex((item) => {
      return item.id == val.id;
    });
    this.data.checkData.splice(index, 1);
    this.setData({
      checkData: this.data.checkData
    })
  },
  onLoad(options) {
    /*     disease=霍乱&main=21122&medical=[{"id":4,"type":"非处方药","pic":"files/admin/20241217/20241217133448_感冒清.jpg","name":"维塔利胶囊","common_name":"维塔利胶囊","price":"128.00","introduce":"维塔利胶囊维塔利胶囊维塔利胶囊","size":"15/次","ingredient":"甲钴胺","feature":"--","save":"--","note":"--","guide":"--","created_at":"2024-12-17 13:35:17","updated_at":"2024-12-17 13:35:17","checkStep":false,"count":"1","doseFrequency":"2","days":"2","precautions":"2","num":"2"}] */
    this.setData({
      'opt.disease': options.disease,
      'opt.disease_code': options.disease_code,
      'opt.main': options.main,
      checkData: options.medical != 'undefined' ? JSON.parse(options.medical) : [],
      isReview: options.isReview,
      activeCode: options.activeCode,
    })
    if (this.data.checkData.length > 0) {
      this.data.medicineArr.forEach(item => {
        item.checked = true
      })
      this.setData({
        active: this.data.checkData[0].DrugClassCode
      })
    }
    this.getMedicList(this.data.active)
    /*    获取频次 */
    this.getFrequencyData()
    //获取用法
    /*   this.getMedicine() */
  },
  getMedicine(DrugModeName) {
    getMedicineTakeTypeData({
      DrugModeName
    }).then(res => {
      res.data.forEach(item => {
        item.text = item.DrugModeName
      })
      this.setData({
        usagefrequencyArr: res.data
      })
    })
  },
  getFrequencyData(DrugFreName) {
    getMedicineFrequencyData({
      DrugFreName
    }).then(res => {
      res.data.forEach(item => {
        item.text = item.DrugFreName
      })
      this.setData({
        frequencyArr: res.data
      })
    })
  },


  /* 煎煮法点击 */
  decoctingClick(e) {
    let index = e.currentTarget.dataset.index
    this.setData({
      usageshowpopup: true,
      decoctingIndex: index,
    })
    this.getDataCN()
  },
  getDataCN(DecoctionName) {
    getJADataCN({
      DecoctionName
    }).then(res => {
      res.data.forEach(item => {
        item.text = item.DecoctionName
      })
      this.setData({
        usagefrequencyArr: res.data,
      })
    })
  },


  submitClick() {
    if (this.data.active == '003') {
      if (!this.data.decocting) {
        wx.showToast({
          title: '请输入用法',
          icon: 'error',
        })
        return
      }
      if (!this.data.dosesNumber) {
        wx.showToast({
          title: '请输入剂数',
          icon: 'error',
        })
        return
      }
    }

    if (this.data.checkData.length > 0) {
      //如果是中草药，将其用法加入进去
      if (this.data.active == '003') {
        this.data.checkData.forEach(item => {
          item.decocting = this.data.decocting
          item.decoctingCode = this.data.decoctingCode
          item.dosesNumber = this.data.dosesNumber
          item.num = this.data.dosesNumber
        })
      }
      let msgData = wx.getStorageSync('messageDetail')
      if (msgData) {
        let subData = {
          order_id: msgData.consultation_order_id,
          uid: msgData.uid,
          patient_id: msgData.patient_id,
          ...this.data.opt,
          medical: this.data.checkData,
        }

        if (this.data.checkData[0].DrugClassCode != '003') {
          wx.navigateTo({
            url: `/pagesDoctor/prescriptionPreview/index?subData=${JSON.stringify(subData)}`,
          })
        } else {
          wx.navigateTo({
            url: `/pagesDoctor/prescriptionPreviewChinese/index?subData=${JSON.stringify(subData)}`,
          })
        }
      }

      /*       wx.setStorageSync('chineseMedicine', val)
            wx.navigateTo({
              url: '/pagesDoctor/prescribeMedicineDataChinese/index',
            }) */


    } else {
      wx.showToast({
        title: '请选择药品',
        icon: 'error'
      })
    }
  },




  onChange(event) {
    /*   wx.showToast({
        title: `切换到标签 ${event.detail.name}`,
        icon: 'none',
      }); */
    this.setData({
      "checkData": [],
      medicineArr: [],
      value: '',
      'params.page': 1,
      active: event.detail.name
    })
    this.getMedicList(this.data.active)
  },

  //填写选中的值
  onChangeCheckData(e) {
    const index = e.currentTarget.dataset.index
    const type = e.currentTarget.dataset.v
    const value = e.detail
    this.setData({
      [`checkData[${index}].${type}`]: value
    })
  },


  handleTap() {

  },

  getMedicList(val, name) {
    console.log(val)
    /*   if (val == '西药') {
        wx.setStorageSync('preDataChines', null)
      } else {
        wx.setStorageSync('preData', [])
      } */
    wx.showLoading({
      title: '加载中'
    })
    let DoctorCommentListDat = []
    ApiGetMedicineList({
      DrugClassCode: val,
      ...this.data.params,
      name
    }).then(res => {
      wx.hideLoading()
      //是否显示选择数量
      res.data.forEach(item => {
        item.checkStep = false
        item.count = '1'
        item.checked = false
      })
      if (name) {
        this.setData({
          medicineArr: res.data
        })
        return
      }
      const data = res.data
      DoctorCommentListDat = this.data.params.page === 1 ? data : this.data.medicineArr.concat(data)
      this.data.params.finish = DoctorCommentListDat.length >= res.page.total
      this.setData({
        'opt.prescription_class': val == '001' ? '1' : '2',
        medicineArr: DoctorCommentListDat,
        loading: false
      })


    })
  },

  medicineClick(e) {
    let value = e.currentTarget.dataset.v
    wx.navigateTo({
      url: `/pagesDoctor/prescribeMedicineDataDetail/index?data=${JSON.stringify(value)}`,
    })
  },


  //切换药品
  /*   onChangecCheckBox(e) {
      this.setCheckData(e.detail)
      this.setData({
        'ops.checkResult': e.detail
      })
      this.getSumData()
    }, */
  handleStop() {},

  confirmBtn(e) {
    this.setData({
      [`checkData[${this.data.freIndex}].frequency`]: e.detail.value.DrugFreName
    })
    this.onClose()
  },
  usageconfirmBtn(e) {
    console.log(e)
    let val = e.currentTarget.dataset.v
    if (val == '003') {
      this.setData({
        'decocting': e.detail.value.DecoctionName,
        'decoctingCode': e.detail.value.DecoctionCode
      })
    } else {
      this.setData({
        [`checkData[${this.data.usageIndex}].usage`]: e.detail.value.DrugModeName
      })
    }

    this.usageonClose()
  },


  frequencyClick(e) {
    this.setData({
      showpopup: true,
      freIndex: e.currentTarget.dataset.index
    })
  },

  usageClick(e) {
    this.getMedicine()
    this.setData({
      usageshowpopup: true,
      usageIndex: e.currentTarget.dataset.index
    })
  },
  //用法进行搜索
  setUserNameIndexes(e) {
    if (this.data.active != '003') {
      this.getMedicine(e.detail)
    } else {
      this.getDataCN(e.detail)
    }
  },
  searchFrequency(e) {
    this.getFrequencyData(e.detail)
  },


  usageonClose() {
    this.setData({
      usageshowpopup: false,
      decoctingMethodshowpopup: false
    })
  },
  onClose() {
    this.setData({
      showpopup: false,
    })
  },


  /*  setCheckData(id) {
     const medicineArr = this.data.medicineArr.map(item => {
       // 如果数组一中包含当前元素的 id，则修改 ischeck 为 true
       if (id.includes(item.id.toString())) {
         item.checkStep = true;
       } else {
         item.checkStep = false
       }
       return item;
     })
     this.setData({
       medicineArr
     })
   }, */

  //切换步进
  /*  onChangeStep(e) {
     console.log(e)
     let index = e.currentTarget.dataset.index
     let oldPrice = this.data.medicineArr[index].price
     this.data.medicineArr[index].count = e.detail
     this.data.medicineArr[index].sumPrice = Number(e.detail) * Number(oldPrice)
     this.getSumData()
   }, */

  //汇总合计数据
  /*   getSumData() {
      console.log('this.data.medicineArr', this.data.medicineArr)
      this.data.medicine = []
      this.data.sum = 0
      this.data.medicineArr.forEach(item => {
        if (this.data.ops.checkResult.includes(item.id.toString())) {
          this.data.sum += item.sumPrice ? item.sumPrice : Number(item.price)
          this.data.medicine.push({
            id: item.id,
            count: item.count,
            price: item.price,
            name: item.name
          })
        }
      })
      this.setData({
        sum: this.data.sum,
        medicine: this.data.medicine
      })
    }, */

  //去缴费

  onClickButton() {
    wx.navigateTo({
      url: `/pages/payment/index?medicine=${JSON.stringify(this.data.medicine)}&&sum=${this.data.sum}`,
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})